package com.bogo.dbtable.handler;

import com.bogo.dbtable.modelVo.result.ApiResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLException;

/**
 * @Author: CHICHI
 * @Date: 2025-05-19-11:11
 * @Description:
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    // 拦截 SQLException 并转换为自定义响应
    @ExceptionHandler(SQLException.class)
    public ResponseEntity<ApiResult> handleSQLException(SQLException e) {
        String errorMessage = e.getMessage();
        int errorCode = 10010; // 自定义错误码

        // 检查是否是 "Incorrect column specifier for column" 错误
        if (errorMessage.contains("Incorrect column specifier for column")) {
            errorMessage = "自增列定义不正确，请检查数据类型和约束";
            errorCode = 10011; // 更具体的错误码
        }
        ApiResult result =new ApiResult();
        result.setCode(errorCode);
        result.setMsg(errorMessage);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }

    // 拦截自定义 DatabaseOperationException
    @ExceptionHandler(DatabaseOperationException.class)
    public ResponseEntity<ApiResult> handleDatabaseOperationException(DatabaseOperationException e) {
        ApiResult result = new ApiResult();
        result.setCode(e.getErrorCode());
        result.setMsg(e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }
}
